import { message } from "antd";


// 列表数据转换
export function convertApiIndex(response: any) {
  let newRes: any = {}
  if (response.code === 0) {
    const { data, code, msg } = response
    newRes.data = data.list
    newRes.common = data.common || {}
    newRes.total = data.pagination.total
    newRes.current = data.pagination.current
    newRes.pageSize = data.pagination.pageSize
    newRes.msg = msg
    newRes.code = code
  }else{
    message.error(response.message);
  }


  // todo  code > 0

  return newRes
}

/**
 * todo 如有新增字段，需要加入进来
 */
export const formatCurrentStateData = (response: any) => {
  if(response.code != 0){
    message.error(response.message);
  }
  return {
    code: response.code,
    msg: response.msg,
    data: {
      listData: {
        data: response.data.list || [],
        ...response.data.pagination
      },
      common: response.data.common || {},
      detail: response.data.detail || {},
      statistical: response.data.statistical || {},
      total: response.data.total || {},
      data: response.data.list || [],
      customer: response.data.customer || {}
    },
  }
}


interface ExecParams {
  fn: (params?: any) => Promise<any>;
  args: any;
  successMsg?: string;
  failMsg?: string;
  hasCallBack?: boolean;
  hasLoading?: boolean;
}

/**
 * 通用请求执行官
 * @returns 默认返回是boolean类型，如果参数 hasCallBack == true, 将返回一个Promise
 * @hasCallBack 是否支持回调(返回一个Promise, 可获取到res, res.execStatus:boolean 判断是成功或失败的回调)
 * @hasLoading 是否显示loading, 默认显示。
 */
export const bdExec = (params: ExecParams) => {
  let hide = () => { };
  if (typeof params.hasLoading == 'undefined' || params.hasLoading == true) {
    hide = message.loading('');
  }
  return params.fn(params.args).then((res) => {
    if (res.code === 0) {
      res.execStatus = true;
      hide();
      params.successMsg && message.success(params.successMsg);
      if (params.hasCallBack) {
        return new Promise((resolve, reject) => resolve(res));
      }
      return true;
    } else {
      res.execStatus = false;
      hide();
      message.error(res.msg);
      params.failMsg && message.error(params.failMsg);
      if (params.hasCallBack) {
        return new Promise((resolve, reject) => resolve(res));
      }
      return false;
    }
  }).catch((error = '') => {
    hide();
    message.error(error);
    return false;
  })
}

